#include "class_log.h"
#include "client.h"


class_log::class_log()
{
r = 0;
w = 0;
}


class_log::~class_log()
{
sync();

std::string msg_data;
while(msg_deque.size() > 0)
{
lock.begin();
msg_data=msg_deque.front();
msg_deque.pop_front();
lock.end();
client_msg(msg_data);
}

}


//  插入一条日志，第一个参数做文件名，第二个参数做内容
int class_log::insert(std::string head, std::string body)
{
	std::stringstream str;
timeval tv;
gettimeofday(&tv,NULL);
tm *tmm=localtime(&tv.tv_sec);
str<<tmm->tm_hour<<"点"<<tmm->tm_min<<"分"<<tmm->tm_sec<<"秒"<<tv.tv_usec/1000<<"毫秒"<<tmm->tm_year+1900<<"年"<<tmm->tm_mon+1<<"月"<<tmm->tm_mday<<"日"<<std::endl<<body<<std::endl;

lock.begin();
log_map_deque[head].push_back(str.str());
lock.end();
++r;
return 0;
}


//插入发信息内容
int class_log::msg(std::string str)
{
if(str.length() == 0) { return 0;}

lock.begin();
msg_deque.push_back(str);
lock.end();
return 0;
}


//吧队列中的内容同步到磁盘
int class_log::sync()
{

if(msg_deque.size() > 0)
{
std::string msg_data;

lock.begin();
msg_data=msg_deque.front();
lock.end();

if(client_msg(msg_data) == 0)
{
lock.begin();
msg_deque.pop_front();
lock.end();
}
}

//下面写磁盘
for(auto at = log_map_deque.begin();at != log_map_deque.end();++at)
{
if(at->second.size() > 0)
{
wj.open(str_log_dz+"/"+at->first+".txt",std::ios_base::app);
while (at->second.size() > 0)
{

wj<<at->second.front();

lock.begin();//进入临界区
at->second.pop_front();//删除第一条
lock.end();//离开临界区
++w;
}
wj.close();
}

}

return 0;
}


int class_log::init(std::string str_dz)
{
str_log_dz =str_dz; 
return 0;
}
